<template>
  <!-- 单行组件：文本、范围选择器、slot -->
  <div
    v-if="prefix && prefixWidth != 0"
    class="any-outsidebar"
  >
    <div
      :class="required ? 'any-prefix' : 'any-prefix2'"
      :style="
        prefixWidth ? 'min-width:' + prefixWidth + ';width:' + prefixWidth : ''
      "
    >
      {{ prefix }}
    </div>
    <!-- 自定义选项 -->
    <el-select
      v-if="type == 'select'"
      :style="selectStyle"
      v-model="elValue"
      :value-key="selectLabelkey"
      multiple
      collapse-tags
      :placeholder="startPlaceholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    >
      <el-option
        v-for="(item, index) in selectOption"
        :key="index"
        :label="item && typeof item == 'object' ? item[selectLabelkey] : item"
        :value="
          selectValuekey && item && typeof item == 'object'
            ? item[selectValuekey]
            : item
        "
      ></el-option>
    </el-select>
    <!-- 时间 -->
    <el-time-picker
      v-else-if="type == 'time'"
      :style="selectStyle"
      v-model="elValue"
      is-range
      range-separator="至"
      :start-placeholder="startPlaceholder"
      :end-placeholder="endPlaceholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    >
    </el-time-picker>
    <!-- 日期 -->
    <el-date-picker
      v-else-if="type == 'month' || type == 'date' || type == 'datetime'"
      :style="selectStyle"
      v-model="elValue"
      :type="elType"
      :picker-options="pickerOption"
      range-separator="至"
      :start-placeholder="startPlaceholder"
      :end-placeholder="endPlaceholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    ></el-date-picker>
    <!-- 地区 -->
    <el-cascader
      v-else-if="type == 'province' || type == 'city' || type == 'district'"
      :style="selectStyle"
      v-model="elValue"
      :options="areaArray"
      :props="{ multiple: true }"
      separator="-"
      :placeholder="startPlaceholder"
      :disabled="disabled"
      size="medium"
      clearable
      @change="changeClick"
    >
    </el-cascader>
    <!-- 扩展slot -->
    <slot name="suffix"></slot>
  </div>

  <!-- 单个范围选择器 -->
  <!-- 自定义选项 -->
  <el-select
    v-else-if="type == 'select'"
    :style="selectStyle"
    v-model="elValue"
    :value-key="selectLabelkey"
    multiple
    collapse-tags
    :placeholder="startPlaceholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  >
    <el-option
      v-for="(item, index) in selectOption"
      :key="index"
      :label="item && typeof item == 'object' ? item[selectLabelkey] : item"
      :value="
        selectValuekey && item && typeof item == 'object'
          ? item[selectValuekey]
          : item
      "
    ></el-option>
  </el-select>
  <!-- 时间 -->
  <el-time-picker
    v-else-if="type == 'time'"
    :style="selectStyle"
    v-model="elValue"
    is-range
    range-separator="至"
    :start-placeholder="startPlaceholder"
    :end-placeholder="endPlaceholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  ></el-time-picker>
  <!-- 日期 -->
  <el-date-picker
    v-else-if="type == 'month' || type == 'date' || type == 'datetime'"
    :style="selectStyle"
    v-model="elValue"
    :type="elType"
    :picker-options="pickerOption"
    range-separator="至"
    :start-placeholder="startPlaceholder"
    :end-placeholder="endPlaceholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  ></el-date-picker>
  <!-- 地区 -->
  <el-cascader
    v-else-if="type == 'province' || type == 'city' || type == 'district'"
    :style="selectStyle"
    v-model="elValue"
    :options="areaArray"
    :props="{ multiple: true }"
    separator="-"
    :placeholder="startPlaceholder"
    :disabled="disabled"
    size="medium"
    clearable
    @change="changeClick"
  >
  </el-cascader>
</template>

<script>
import anyfishUI from "../../index";
export default {
  name:"mm-select-range",
  props: {
    selectStyle: {// 选择框样式
      type: String,
      default: null
    },

    obj: {// InputObj
      type: Object,
      default: function () {
        return null;
      }
    },

    objKey: {// 数据对应InputObj的key值
      type: String,
      default: ""
    },

    prefix: {// 左边的文本内容
      type: String,
      default: null
    },

    prefixWidth: {// 左边的文本宽度：3.6rem、10px、20%等，为0则不显示，为空则自适应
      type: String,
      default: null
    },

    /**
     * 自定义选项（对应selectOption、selectLabelkey、selectValuekey）：select
     * 时间：time
     * 日期：month、date、datetime
     * 地区：province、city、district
     */
    type: {
      type: String,
      default: "select"
    },

    selectOption: {// 对应select的数组
      type: Array,
      default: null
    },

    selectLabelkey: {// 对应select的数组的显示值的key
      type: String,
      default: null
    },

    selectValuekey: {// 对应select的数组的选中值的key
      type: String,
      default: null
    },

    startLimitDate: {// 限制的开始日期，可为字符串、时间戳、date，单位秒
      type: Object | Date,
      default: null
    },

    endLimitDate: {// 限制的结束日期，可为字符串、时间戳、date，单位秒
      type: Object | Date,
      default: null
    },

    startPlaceholder: {// 左边选择框为空时的提示文字
      type: String,
      default: null
    },

    endPlaceholder: {// 右边选择框为空时的提示文字
      type: String,
      default: null
    },

    required: {// 是否必填
      type: Boolean,
      default: false
    },

    disabled: {// 是否不可用
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      elValue: null,
      pickerOption: {
        disabledDate: (date) => {
          if (date) {
            let time = date.getTime();
            if (time > 0) {
              if (this.startLimitTime > 0 && this.startLimitTime > time) {
                return true;
              }
              if (this.endLimitTime > 0 && this.endLimitTime < time) {
                return true;
              }
            }
          }
          return false;
        }
      }
    }
  },

  computed: {
    elType() {
      if (this.type == "month") {
        return "monthrange";
      }
      if (this.type == "date") {
        return "daterange";
      }
      if (this.type == "datetime") {
        return "datetimerange";
      }
      return null;
    },

    startLimitTime() {
      if (this.startLimitDate) {
        let date = anyfishUI.api.getDateByType(this.startLimitDate);
        if (date != null) {
          return date.getTime();
        }
      }
      return 0;
    },

    endLimitTime() {
      if (this.endLimitDate) {
        let date = anyfishUI.api.getDateByType(this.endLimitDate);
        if (date != null) {
          return date.getTime();
        }
      }
      return 0;
    },

    areaArray() {
      if (this.type == "province" || this.type == "city" || this.type == "district") {
        let baseArea = require("../../engine/baseArea");
        let array = [];
        for (let i in baseArea) {
          let srcItem = baseArea[i];
          let item = {};
          item.value = srcItem.n;
          item.label = srcItem.n;
          if (this.type == "city" || this.type == "district") {
            item.children = [];
            for (let j in srcItem.c) {
              let srcSubItem = srcItem.c[j];
              let subItem = {};
              subItem.value = srcSubItem.n;
              subItem.label = srcSubItem.n;
              if (this.type == "district") {
                subItem.children = [];
                for (let k in srcSubItem.c) {
                  let srcPopItem = srcSubItem.c[k];
                  let popItem = {};
                  popItem.value = srcPopItem.n;
                  popItem.label = srcPopItem.n;
                  subItem.children.push(popItem);
                }
              }
              item.children.push(subItem);
            }
          }
          array.push(item);
        }
        return array;
      }
      return null;
    }
  },

  watch: {
    obj() {
      this.register();
    },

    objKey() {
      this.register();
    },

    type() {
      this.changeClick(null);
    }
  },

  mounted() {
    this.register();
  },

  destroyed() {
    this.obj._unRegister(this.objKey);
  },

  methods: {
    register() {
      let self = this;
      this.obj._watch(this.objKey, function (value) {
        self.elValue = value;
      });
      this.obj._register(this.objKey, function () {
        let prefix = self.prefix;
        if (!prefix) {
          let type = self.type;
          if (type == "month" || type == "date" || type == "datetime") {
            prefix = "日期";
          } else if (type == "time") {
            prefix = "时间";
          } else if (type == "province" || type == "city" || type == "district") {
            prefix = "地区";
          } else {
            prefix = "内容";
          }
        }
        return self.checkData(self.obj[self.objKey], self.required, prefix);
      });
    },

    checkData(data, required, prefix) {
      if (!required) {
        return true;
      }
      if (data == undefined || data == null) {
        anyfishUI.api.toast("请选择" + prefix);
        return false;
      }
      if ((typeof data == "string" ? data.trim() : data + "").length < 1) {
        anyfishUI.api.toast("请选择" + prefix);
        return false;
      }
      return true;
    },

    changeClick(value) {
      this.obj[this.objKey] = value;
      this.$emit("change", value);
    }
  }
}
</script>

<style scoped>
.any-outsidebar {
  margin: 0.5rem 1rem;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: row;
  align-items: center;
}

.any-prefix2 {
  margin-right: 0.5rem;
  font-size: 0.8rem;
  text-align: center;
  white-space: nowrap;
  user-select: none;
  -webkit-user-select: none;
}

.any-prefix {
  margin-right: 0.5rem;
  font-size: 0.8rem;
  text-align: center;
  white-space: nowrap;
  user-select: none;
  -webkit-user-select: none;
}

.any-prefix::before {
  margin: 1px;
  color: #ee0a24;
  font-size: 14px;
  content: "*";
}
</style>